<?php

namespace addons\shopro\job;

use addons\shopro\service\commission\Agent as AgentService;
use app\admin\model\shopro\commission\Agent;
use app\admin\model\shopro\commission\MonthlyCompliance;
use app\admin\model\shopro\Config as ShoproConfig;
use app\admin\model\shopro\Performance;
use think\Log;
use think\queue\Job;
use think\Db;
use think\exception\HttpResponseException;

/**
 * 用户
 */
class User extends BaseJob
{


    public function check_agent(Job $job, $data){
        try {
            $id=$data["user_id"];
            $model=new  \app\admin\model\User();
            $user =$model->where("id",$id)->find();
            $this->find($id,$user["parent_user_id"]);
            $job->delete();
        } catch (HttpResponseException $e) {
            $data = $e->getResponse()->getData();
            $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
            format_log_error($e, 'User.HttpResponseException', $message);
        } catch (\Exception $e) {
            format_log_error($e, 'User');
        }
    }

    public function find($id,$parent_user_id,$arr=[])
    {
        $user=\app\common\model\User::where(["parent_user_id"=>$id])->select();
        if(!empty($user)){
            foreach ($user as $v){
                if(!empty($parent_user_id)){
                    if($v["id"]==$parent_user_id){
                        //如果下级id等于上级的parent_user_id
                        \think\Log::info('data:'.json_encode($arr).' 我的上级是我的下级：[ID=' .  $parent_user_id. '&nickname=' . $v["nickname"] . '&parent_user_id='.$v["id"].'] ---Ended');
                        \app\common\model\User::where(["id"=>$v["parent_user_id"]])->update(["parent_user_id"=>0]);
                        continue;
                    }
                }
                if(in_array($v["parent_user_id"],$arr)){
                    //如果下级的上级id在下级id数组中
                    \think\Log::info('data:'.json_encode($arr).'[ID=' . $v["id"] . '&nickname=' . $v["nickname"] . '&parent_user_id='.$v["parent_user_id"].'] ---Ended');
                    \app\common\model\User::where(["id"=>$v["parent_user_id"]])->update(["parent_user_id"=>0]);
                    continue;
                }
                $arr=array_merge($arr,[$v["id"]]);
                $this->find($v["id"],$v["parent_user_id"],$arr);
            }
        }
    }
}
